package com.xmut.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmut.mall.product.constant.ProductConstant;
import com.xmut.mall.product.dao.AttrAttrgroupRelationDao;
import com.xmut.mall.product.dao.AttrGroupDao;
import com.xmut.mall.product.dao.CategoryDao;
import com.xmut.mall.product.entity.AttrAttrgroupRelationEntity;
import com.xmut.mall.product.entity.AttrGroupEntity;
import com.xmut.mall.product.entity.CategoryEntity;
import com.xmut.mall.product.service.CategoryService;
import com.xmut.mall.product.utils.RespBean;
import com.xmut.mall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.product.utils.PageUtils;
import com.xmut.mall.product.utils.Query;

import com.xmut.mall.product.dao.AttrDao;
import com.xmut.mall.product.entity.AttrEntity;
import com.xmut.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if(catelogId != 0){
            queryWrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            //attr_id  attr_name
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //1、设置分类和分组的名字
            if("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity attrId = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrId != null && attrId.getAttrGroupId()!=null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }

            }


            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();

        BeanUtils.copyProperties(attr,attrEntity);
        // 保存基本数据
        this.save(attrEntity);
        // 保存关联关系
        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,respVo);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            // 设置分组信息
            AttrAttrgroupRelationEntity attrgroupRelation = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(attrgroupRelation!=null){
                respVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
                if(attrGroupEntity!=null){
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        respVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity!=null){
            respVo.setCatelogName(categoryEntity.getName());
        }

        return respVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            // 修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());


            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));

            if(count>0){
                relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id",attr.getAttrId()));
            }else {
                relationDao.insert(relationEntity);
            }
        }

    }

    /**
     * 根据分组id查找关联的基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));

        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        relationDao.deleteBatchRelation(entities);
    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1)、当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2)、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3)、从当前分类的所有属性中移除这些属性；
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrsIds(List<Long> attrIds) {

        return baseMapper.selectSearchAttrsIds(attrIds);
    }

    /**
     * 根据当前的catId获取属于当前CateId且可用于检索的attr属性
     * @param cateId
     * @return
     */
    @Cacheable(value = {"Attr"},key = "#root.methodName+#root.args[0]")
    @Override
    public List<AttrEntity> getAbleToSearchAttrByCateId(Long cateId) {
        // 查询属于该cateId且是可进行检索的属性
        return this.baseMapper.selectList(
                new QueryWrapper<AttrEntity>()
                        .eq("catelog_id", cateId)
                        .eq("search_type", 1));

    }

    /**
     * 获取普通属性分页
     * @param params
     * @return
     */
    @Override
    public RespBean getAttrByPage(Map<String, Object> params) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();

        // 模糊匹配属性名
        if(!StringUtils.isEmpty(String.valueOf(params.get("specName"))) && !String.valueOf(params.get("specName")).equals("null")){
            queryWrapper.like("attr_name", String.valueOf(params.get("specName")));
        }

        // 匹配是销售属性还是基本属性
        if(!StringUtils.isEmpty(String.valueOf(params.get("attrType"))) && !String.valueOf(params.get("attrType")).equals("null")){
            queryWrapper.eq("attr_type",Integer.parseInt(String.valueOf(params.get("attrType"))));
        }

        // 匹配分类
        if(!StringUtils.isEmpty(String.valueOf(params.get("catelogId"))) && !String.valueOf(params.get("catelogId")).equals("null")){
            queryWrapper.eq("catelog_id",Long.parseLong(String.valueOf(params.get("catelogId"))));
        }

        // 排序
        if(String.valueOf(params.get("order")).equals("asc")){
            queryWrapper.orderByAsc(String.valueOf(params.get("sort")));
        }else{
            queryWrapper.orderByDesc(String.valueOf(params.get("sort")));
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

//        return new PageUtils(page);

        return RespBean.success("获取成功", new PageUtils(page));

    }

    /**
     * 添加属性
     * @param vo
     * @return
     */
    @Override
    public RespBean addAttr(AddAttrVo vo) {
        AttrEntity attr = new AttrEntity();
        attr.setAttrName(vo.getSpecName());
        StringBuffer stringBuffer = new StringBuffer();
        for (String s : vo.getSpecValue()) {
            stringBuffer.append(s+";");
        }
        attr.setValueSelect(stringBuffer.toString());
        attr.setCatelogId(vo.getCatelogId());
        attr.setAttrType(vo.getAttrType());

        attr.setCreateTime(new Date());

        // 保存
        boolean save = this.save(attr);
        if (save){
            return RespBean.success("保存成功");
        }else {
            return RespBean.error("保存失败");
        }

    }

    /**
     * 编辑attr信息
     * @param vo
     * @return
     */
    @Override
    public RespBean editAttr(UpdateAttrVo vo) {
        AttrEntity attr = new AttrEntity();
        attr.setAttrId(vo.getId());
        attr.setCatelogId(vo.getCatelogId());
        attr.setAttrType(vo.getAttrType());
        attr.setAttrName(vo.getSpecName());
        StringBuffer stringBuffer = new StringBuffer();
        for (String s : vo.getSpecValue()) {
            stringBuffer.append(s+";");
        }
        attr.setValueSelect(stringBuffer.toString());

        boolean save = this.updateById(attr);
        if (save){
            return RespBean.success("修改成功");
        }else {
            return RespBean.error("修改失败");
        }
    }

    /**
     * 批量删除属性
     * @param ids
     * @return
     */
    @Override
    public RespBean deleteAttr(List<Long> ids) {
        boolean b = this.removeByIds(ids);
        if (b){
            return RespBean.success("删除成功");
        }else {
            return RespBean.error("删除失败");
        }

    }

    /**
     * 根据cate分类获取销售属性
     * @param cateId
     * @return
     */
    @Override
    public RespBean getSaleAttr(Long cateId) {
        List<AttrEntity> saleAttr = this.list(new QueryWrapper<AttrEntity>().eq("attr_type", 0));
        return RespBean.success("获取成功",saleAttr);
    }

}